package com.lry.basic.redis;

import java.io.IOException;
import java.net.Socket;

public class RedisResp {

    private Socket socket;

    public RedisResp() {
        try {
            socket = new Socket("localhost", 6379);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("连接失败" + e.getMessage());
        }
    }

    /**
     * 设置值
     * @param key
     * @param value
     * @return
     * @throws IOException
     */
    public String set(String key, String value) throws IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("*3").append("\r\n");
        sb.append("$").append(3).append("\r\n");
        sb.append("set").append("\r\n");
        // 注意中文汉字。一个汉字两个字节，长度为2,所以不可以直接length
        sb.append("$").append(key.getBytes().length).append("\r\n");
        sb.append(key).append("\r\n");
        sb.append("$").append(value.getBytes().length).append("\r\n");
        sb.append(value).append("\r\n");
        System.out.println(sb.toString());

        socket.getOutputStream().write(sb.toString().getBytes());
        byte[] b = new byte[2048];
        socket.getInputStream().read(b);
        return new String(b);
    }

    /**
     * 获取值
     * @param key
     * @return
     * @throws Exception
     */
    public String get(String key) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("*2").append("\r\n");
        stringBuffer.append("$").append(3).append("\r\n");
        stringBuffer.append("get").append("\r\n");
        stringBuffer.append("$").append(key.getBytes().length).append("\r\n");
        stringBuffer.append(key).append("\r\n");

        socket.getOutputStream().write(stringBuffer.toString().getBytes());
        byte[] b = new byte[2048];
        socket.getInputStream().read(b);
        return new String(b);
    }

    public static void main(String[] args) throws Exception {
        RedisResp resp = new RedisResp();
        System.out.println(resp.set("key" ,"value"));
        System.out.println(resp.get("key"));
    }
}